<?php

namespace app\admin\controller;

use app\admin\model\Bot;
use App\admin\validate\Bot as ValidateBot;
use App\telegram\FileType;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use plugin\admin\app\controller\Base;
use plugin\admin\app\model\User;
use support\Cache;
use support\Log;
use support\Request;
use GuzzleHttp\Client;

use Respect\Validation\Exceptions\ValidationException;
use support\Db;
use support\Response;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramResponseException;
use Telegram\Bot\FileUpload\InputFile;
use Telegram\Bot\BotsManager;
use Telegram\Bot\Objects\Update;
use Telegram\Bot\Keyboard\Keyboard;
use support\Redis;
use Webman\RedisQueue\Redis as RedisQueue;


class ApiController extends Base
{
    private $telegram;
    private $update;
    private $rediskey;
    private $user_now;
    private $chat_id;
    private $message_id;
    private $beifen_name = "huoyunseo";
//    private $beifen_token = "7205363708:AAG-_CH37LDK_XEaSbOxeRR4kcj6zpUwB3k";
    private $beifen_token = "7264181945:AAEkf5eJ06QREetU8y0kTccliRAxWUv8WFg";
    private $beifen_id = "5868952909";


    private $bot_name = "tzhizi_bot";
    private $bot_bottoken = "7264181945:AAEkf5eJ06QREetU8y0kTccliRAxWUv8WFg";
    private $bot_pindao = "tianzhiazzbot";

    /**
     * 创建机器人
     *
     * @var string
     */
    public function index(){
        //设置hook地址
        $telegram = new Api($this->bot_bottoken);
        $params = [
            'url'         => getTelegramHookUrl($this->bot_bottoken),
        ];
        $res = $telegram->setWebhook($params);
        dump($res);
        return 'success';
    }

    /**
     * 消息处理
     */
    public function hook($token,Request $request){
        $telegram = new Api($this->bot_bottoken);
        $this->telegram = $telegram;
        $updates = $request->all();
        dump($updates);
        //$updates = $telegram->getWebhookUpdate(true);//使用接口获取数据(不能使用)
        file_put_contents(base_path('aaa.txt'), json_encode($updates));
        $update = new Update($updates);
        $this->update = $update;
        $rediskey = $this->bot_name.'_'.$this->chat_id;
        $this->rediskey = $rediskey;
        $message =  $this->update->getMessage();
        $this->message = $message;
        $reply_to_message_id = $update->getMessage()->get('message_id');
        $this->reply_to_message_id = $reply_to_message_id;
        $message = $update->getMessage();
        $type =  $message->objectType();
        $text = $message->text;
        $this->chat_id =  $this->update->getChat()?->id;
        $this->message_id =  $message->get("message_id");


        //取消的消息能不能获取到
        dump($update->objectType());

//        Redis::del($this->rediskey);
//        dump("success2");
//        return "success";

        //确认是否关注
        $res = $telegram->getChatMember(["chat_id"=>"@{$this->bot_pindao}","user_id"=> $this->chat_id]);
        if ($res->status == 'left'){
            //请关注
            return $this->guanzhu_vertify();
        }else{
            $guanzhuredis_key = $this->rediskey."-guanzhu";
            Redis::del($guanzhuredis_key);
        }
        //鉴权是否注册 并关注
        if ($text != '/start'){
            $user_now = Db::table("wa_users")
                ->where('chat_id','=', $this->chat_id)
                ->where('password','!=', '')
                ->first();
            if (!$user_now){
                return $this->sendnomessage('麻烦您先发送 /start 再使用本机器人！');
            }
            $this->user_now = $user_now;
        }

        // 按钮类消息
        if($update->isType('callback_query')){
            $data = explode(' ',$update->getRelatedObject()->get('data'));
            $function = $data[0].'_callback';
            dump($function);
            dump($data);
            return $this->$function($data);
        }
        // 直发类消息
        if($update->isType('message')){
            //1. 防止重复消息 (未完成) 要不要 使用redis 替代
            $update_id = Db::table("wa_file")->where("update_id",'=',$update->get("update_id"))->first();
            if ($update_id){
                dump("重复消息success");
                return 'success';
            }

            dump("消息类型:{$type}");
            dump($text);

            //任务执行中消息 处理redis命令 pk_setpassword
            $redisdata = Redis::get($rediskey);
            if ($redisdata != false){
                $redisdata = json_decode($redisdata,true);
                dump("处理redis命令",$redisdata);
                $function = $redisdata['command']."_redis";
                dump("处理redis命令",$function);
                return $this->$function($text,$redisdata);
            }

            // 直发文件类消息处理
            if($message->isType('photo') || $message->isType('animation') || $message->isType('audio') || $message->isType('document') || $message->isType('video')  || $message->isType('video_note') || $message->isType('voice')){
                //文件存档
                return $this->setFileLink();
            }

            // 直发文本类消息处理
            if($message->isType('text')){
                $file_id = '';
                //如果是命令是数据库的命令,则进行处理

                //处理命令消息
                if ($text[0] === '/'){
                        //处理 /pk //待整理
                        $text_arr = explode(' ',$text);
                    dump("处理消息命令",$text_arr);

                        if ($text_arr[0] == '/pk' && count($text_arr)>1){
                            //写入打包数据库
                            unset($text_arr[0]);
                            sort($text_arr);
                            $value = json_encode($text_arr);
                            $link = $this->setLink('package',$value);
                            $existingRecord = Db::table("wa_package")
                                ->where('link','=',$link)
                                ->where('uid','=',$this->user_now->id)
                                ->first();
                            if ($existingRecord){
                                return $this->sendnomessage("打包文件已存在");
                            }
                            $pk_insert = [
                                'created_at' => date("Y-m-d H:i:s",time()),
                                'updated_at' => date("Y-m-d H:i:s",time()),
                                'link' => $link,
                                'value' => $value,
                                "password" => '',
                                "usenum" => 0,
                                "username" => $update->getChat()?->username,
                                "uid" => $this->user_now->id,
                            ];

                            $res = Db::table("wa_package")->upsert($pk_insert,['link','username']);
                            dump("新增结果{$res}");

                            $reply_markup = Keyboard::make()
                                ->inline()
                                ->setResizeKeyboard(true)
                                ->setOneTimeKeyboard(true)
                                ->row([
                                    Keyboard::button(['text'=> '设置密码','callback_data'=> 'pk_setpassword']),
                                ]);

                            $telegram->sendMessage([
                                'chat_id'   =>  $this->chat_id,
                                'text'      =>  "<b>文件合并成功，文件提取码为:</b><code>{$link}</code>",
                                'parse_mode'=> 'html',
                                'reply_markup'=> $reply_markup,
                            ]);

                            dump("success");
                            return "success";
                        }else{

                            $command = Db::table("wa_command")->where("name",'=',$text_arr[0])->first();
                            if ($command){
                                return $this->deal_command($command,$text_arr);
                            }
                        }



                }else{  //处理文本消息  三种 1. pk 打包提取 2.Fo_文件夹提取 3. 文件直接提取
                    $arr = explode("_",$text);
                    dump($arr);
                    //查找文件
                    if ($arr[0] == "PK" || $arr[0] == "pk"){
                        $package =  Db::table("wa_package")
                            ->where("link",'=',$text)
                            ->where("uid",'=',$this->user_now->id)
                            ->first(['value','password','link']);

                        $package = $package ? (array)$package : [];

                        if (!$package){
                            return $this->sendnomessage();
                        }
                        //如果有密码需要输入密码
                        if ($package['password']){
                            $redis_value = [
                                "command" => 'pk_vertifypassword',
                                "reply_to_message_id" => $reply_to_message_id,
                                "link" => $package['value'],
                                "password" => $package['password'],
                            ];
                            Redis::set($rediskey, json_encode($redis_value));
                            $reply_markup = Keyboard::make()
                                ->setResizeKeyboard(true)
                                ->setOneTimeKeyboard(true)
                                ->setSelective(true)
                                ->row([
                                    Keyboard::button(['text'=>'取消']),
                                ]);
                            $telegram->sendMessage([
                                'chat_id'   =>  $this->chat_id,
                                'text'      =>  "请输入密码",
                                'reply_markup'=> $reply_markup,
                                'reply_to_message_id'=> $reply_to_message_id,
                            ]);
                            dump("success");
                            return "success";
                        }
                        //直接发送文件夹
                        $link_arr = $package['value'] ? json_decode($package['value'],true) : [];
                        return $this->sendMsgGroup($link_arr,0);

                    }elseif ($arr[0] == "Fo" || $arr[0] == "fo"){

                        return $this->fd_getfolderfiles_tongyi($text,$reply_to_message_id);

                    } else{
                        $fleinfo = Db::table("wa_file")
                            ->where("link",'=',$text)
                            ->where("bot",'=',$this->bot_name)
                            ->first(["fleinfo","type"]);

                        if ($fleinfo){
                            $type = $fleinfo->type;
                            $method  = 'send'. ucfirst(Str::camel($type));
                            $file_id = $this->getFileId2($fleinfo->fleinfo,$type);
                        }

                        if ($file_id){
                            $telegram->{$method}([
                                'chat_id' => $this->chat_id,
                                $type     =>  $file_id,
                            ]);
                        }else{
                            $telegram->sendMessage([
                                'chat_id'   =>  $this->chat_id,
                                'text'      =>  "未找到该文件",
                            ]);
                        }

                    }

                }
            }
        }

        dump('success');
        return 'success';
    }
    /**
     *  强制关注
     */
    protected function guanzhu_vertify(){
        $guanzhuredis_key = $this->rediskey."-guanzhu";
        $guanzhuredis_value = Redis::get($guanzhuredis_key);
        if ($guanzhuredis_value){
            $this->telegram->deleteMessage([
                'chat_id'   =>   $this->chat_id,
                'message_id'=> $guanzhuredis_value,
            ]);
        }
        $reply_markup = Keyboard::make()
            ->inline()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(true)
            ->row([
                Keyboard::button(['text'=> '使用本机器人,需要先关注官方频道','url'=> "https://t.me/{$this->bot_pindao}"]),
            ]);

        $message_param = [
            'chat_id'   =>   $this->chat_id,
            'text'   =>   "使用本机器人,需要先关注下放的频道,以防失联",
            'reply_markup'   =>   $reply_markup,
        ];
        $res = $this->telegram->sendMessage($message_param);
        dump($this->rediskey."-guanzhu");
        dump($res->get("message_id"));
        Redis::set($this->rediskey."-guanzhu",$res->get("message_id"));
        return "success";
        //return $this->sendmessage_tongyi("使用本机器人,需要先关注下放的频道,以防失联",null,['reply_markup'=> $reply_markup]);
    }

    /**
     *  设置密码,pk_ 设置密码按钮
     */
    protected function pk_setpassword_callback($data){

        $reply_markup = Keyboard::make()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(true)
            ->setSelective(true)
            ->row([
                Keyboard::button(['text'=> '取消']),
            ]);
        dump($reply_markup);
        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  "请设置密码",
            'reply_markup'=> $reply_markup,
            'reply_to_message_id'=> $this->reply_to_message_id,
        ]);
        $text = $this->update->getMessage()->get('text');

        $link = str_replace("文件合并成功，文件提取码为:",'',$text);
        $redis_value = [
            "command" => 'pk_setpassword',
            "reply_to_message_id" => $this->reply_to_message_id,
            "link" => $link,
        ];
        Redis::set($this->rediskey, json_encode($redis_value));

        dump("success");
        return "success";
    }
    /**
     *  添加文件
     */
    protected function fd_add_callback($data){
        $folder = Db::table("wa_folder")->where('id','=',$data[1])->first();
        if (!$folder){
            return $this->sendnomessage("文件夹不存在");
        }
        return $this->insertfile_tongyi('','',$folder->link);
    }
    /**
     *  删除文件  待开发
     */
    protected function fd_delete_callback($data){

        $forder = Db::table("wa_folder")->where('id','=',$data[1])->first();

        if (!$forder){
            return $this->sendnomessage("文件夹不存在");
        }

        $reply_markup = Keyboard::make()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(true)
            ->setSelective(true)
            ->row([
                Keyboard::button(['text'  => 'ok']),
            ]);

        $message_param = [
            'chat_id'       =>   $this->chat_id,
            'text'       =>  "接下来请您发送想要从包中删除的文件吧~\n完成操作后请发送ok, 你也可以点击下面的按钮",
            'reply_markup'       =>  $reply_markup,
        ];
        $res = $this->telegram->sendMessage($message_param);

        $redis_value = [
            "command" => 'fd_delete',
            "forderid" => $forder->id,
            "message_id" =>$res->get("message_id"),
        ];

        Redis::set($this->rediskey,json_encode($redis_value));
        dump("success");
        return "success";
    }
    /**
     *  一键提取
     */
    protected function fd_getlink_callback($data){
        $rediskey = $this->update->getChat()?->username . '-fd-'.$data[1];
        $redisdata = Redis::get($rediskey);
//        if($redisdata){
        if(false){
            return $this->sendnomessage("您近期已经获取过该文件夹");
        }else{
            Redis::set($rediskey,'true',60);
            return $this->fd_getfolderfiles_tongyi($data[1],null);
        }
    }
    /**
     *  提取文件夹文件统一方法
     *  $reply_to_message_id  是否回复
     */
    protected function fd_getfolderfiles_tongyi($link,$reply_to_message_id=null){
        $folder =  Db::table("wa_folder")
            ->where("id",'=',$link)
            ->orWhere("link",'=',$link)
            ->first();
        if (!$folder){
            return $this->sendnomessage("文件夹不存在");
        }
        if ($folder->tiqu == 0 && $this->user_now->id != $folder->uid){
            return $this->sendmessage_tongyi('非常抱歉，创建者取消了此文件夹的分享',$reply_to_message_id);
        }
        $link_arr = Db::table("wa_file")
            ->where("forderid",'=',$folder->id)
            ->pluck("link")->toArray();
        if (!$link_arr){
            return $this->sendmessage_tongyi('暂无文件',$reply_to_message_id);
        }
        $message_param = [];
        $folder->name ?? '未命名';
        $message_param['caption'] = "文件夹名称:{$folder->name}";
        if ($reply_to_message_id){
            $message_param['reply_to_message_id'] = $reply_to_message_id;
        }
        if ($folder->zhuanfa == 0){
            $message_param["protect_content"] = true;
            $message_param['caption'] .= "\n本媒组,创建者设置了禁止转发";
        }
        Db::table("wa_folder")->where('id','=',$folder->id)->increment('usenum');
        return $this->sendMsgGroup($link_arr,$folder->id,$message_param);
    }
    /**
     *  修改分享链接
     */
    protected function fd_editlink_callback($data){

        $link = $this->setLink('folder', md5($this->update->getChat()?->username.time()));
        Db::table("wa_folder")->where("id",'=',$data[1])->update(['link'=>$link]);
        $message_param = $this->getFileMessage_tongyi($data[1]);
        $message_param['message_id'] = $this->message->get("message_id");

        $this->telegram->editMessageText($message_param);
        Redis::del($this->rediskey);

        dump('success');
        return 'success';
    }
    /**
     *  修改名字
     */
    protected function fd_editname_callback($data){
        $forder = Db::table("wa_folder")->where('id','=',$data[1])->first();
        if (!$forder){
            return $this->sendnomessage("文件夹不存在");
        }
        $params = [
            'text'                                 => '取消修改',
            'callback_data'                        => "fd_editname_quxiao",
        ];
        $reply_markup = Keyboard::make()
            ->inline()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(true)
            ->row([
                Keyboard::button($params),
            ]);

        $res = $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  '将新名字直接发给我就可以',
            'reply_to_message_id'      => $this->message->get("message_id"),
            'reply_markup'  => $reply_markup,
        ]);

        $value = [
            "command"       => "fd_editname",
            "message_id"    => $res->get("message_id"),
            "folderid"      => $data[1],
            "message_id_folder" => $this->message->get("message_id"),
        ];
        Redis::set($this->rediskey,json_encode($value));
        dump("success");
        return "success";
    }
    /**
     *  取消修改名字
     */
    protected function fd_editname_quxiao_callback($data)
    {
        return $this->xiugai_tongyi("您已取消修改",$this->message->get("message_id"));
    }

    /**
     *  查看文件夹列表
     */
    protected function fd_chakanlist_callback($data)
    {
        $message_param =  $this->getMyFolderMessage_tongyi($data[1]);
        $message_param['message_id'] = $this->message->get("message_id");
        $this->telegram->editMessageText($message_param);
        dump("success");
        return "success";
    }

    /**
     *  查看文件夹详情
     */
    protected function fd_chakan_callback($data)
    {
        $message_param = $this->getFileMessage_tongyi($data[1],$data[2]);
        $message_param['message_id'] = $this->message->get("message_id");
        $this->telegram->editMessageText($message_param);
        dump("success");
        return "success";
    }




    /**
     *  当前提取后的内容可转发
     */
    protected function fd_zhuanfa_y_callback($data){

        $zhuanfa = Db::table("wa_folder")->where("id",'=',$data[1])->value('zhuanfa');
        Db::table("wa_folder")->where("id",'=',$data[1])->update(['zhuanfa'=>!$zhuanfa]);
        $message_param = $this->getFileMessage_tongyi($data[1]);
        $message_param['message_id'] = $this->message->get("message_id");
        $this->telegram->editMessageText($message_param);
        Redis::del($this->rediskey);
        dump('success');
        return 'success';

    }
    /**
     *  当前其他人可提取文件夹
     */
    protected function fd_tiqu_y_callback($data){
        $tiqu = Db::table("wa_folder")->where("id",'=',$data[1])->value('tiqu');
        Db::table("wa_folder")->where("id",'=',$data[1])->update(['tiqu'=>!$tiqu]);
        $message_param = $this->getFileMessage_tongyi($data[1]);
        $message_param['message_id'] = $this->message->get("message_id");
        $this->telegram->editMessageText($message_param);
        Redis::del($this->rediskey);
        dump('success');
        return 'success';
    }
    /**
     *  删除文件夹
     */
    protected function fd_shanchu_callback($data){
        $forder = Db::table("wa_folder")->where('id','=',$data[1])->first();
        if ($forder){
            $reply_markup = Keyboard::make()
                ->inline()
                ->setResizeKeyboard(true)
                ->setOneTimeKeyboard(true)
                ->row([
                    Keyboard::button(['text'=> '确定删除','callback_data'=> "fd_shanchu_queding {$forder->id} {$this->message_id}"]),
                    Keyboard::button(['text'=> '取消删除','callback_data'=> "fd_shanchu_quxiao {$forder->id} {$this->message_id}"]),
                ]);
            $res = $this->telegram->sendMessage([
                'chat_id'   =>   $this->chat_id,
                'text'      =>  "您选择了删除文件夹 '{$forder->name}'\n请注意这个操作是不可撤销的，如果您确定的话请点击下方按钮",
                'reply_markup'  => $reply_markup,
            ]);
        }else{
            $this->sendnomessage("文件夹不存在");
        }

        dump("success");
        return "success";
    }
    /**
     *  确定删除
     */
    protected function fd_shanchu_queding_callback($data){
        $forder = Db::table("wa_folder")->where('id','=',$data[1])->first();
        if (!$forder){
            return $this->sendnomessage("文件夹不存在");
        }
        Db::table("wa_folder")->delete($data[1]);
        $this->telegram->deleteMessage([
            'chat_id'   =>   $this->chat_id,
            'message_id'=> $data[2],
        ]);
        return $this->xiugai_tongyi("您已删除文件夹: {$forder->name}",$this->message_id);
    }
    /**
     *  取消删除
     */
    protected function fd_shanchu_quxiao_callback($data){
        return $this->xiugai_tongyi("操作已取消",$this->message->get("message_id"));
    }

    /**
     *  取消文件创建
     */
    protected function fd_quxiao_callback($data){
        return $this->xiugai_tongyi("您已取消创建",$this->message->get("message_id"));
    }
    /**
     *  文件跳过取名
     */
    protected function fd_tiaoguo_callback($data)
    {
        $redisdata = Redis::get($this->rediskey);
        $redisdata = $redisdata ? json_decode($redisdata,true) : [];

        dump($redisdata);
        return $this->insertfile_tongyi('',$redisdata["message_id"]);

    }

    /**
     *  统一修改按钮 仅修改文字
     */
    protected function xiugai_tongyi($text,$message_id){
        Redis::del($this->rediskey);
        $this->telegram->editMessageText([
            'chat_id'       =>   $this->chat_id,
            'text'          =>  $text,
            'message_id'    =>  $message_id,
        ]);
        dump("success");
        return "success";
    }
    /**
     *  统一取消按钮处理 redis任务中的消息 _tongyi
     */
    protected function quxiao_tongyi($text,$reply_to_message_id){
        Redis::del($this->rediskey);
        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  $text,
            'reply_to_message_id'      =>  $reply_to_message_id,
        ]);
        dump("success");
        return "success";
    }


    /**
     *  设置文件夹名称;新增文件夹;添加文件;
     */
    protected function insertfile_tongyi($name='',$message_id='',$link = '')
    {
        $username = $this->update->getChat()?->username;
        //有link 代表新增文件夹  无则不创建直接开始新增
        if ($link == ''){
            $link = $this->setLink('folder',md5($username.time()));
            if (!$name){
                $name = "未命名";
            }
            $insert = [
                'created_at' => date("Y-m-d H:i:s",time()),
                'updated_at' => date("Y-m-d H:i:s",time()),
                'uid' => $this->user_now->id,
                'username' => $this->update->getChat()?->username,
                'name' => $name,
                "link" => $link,
            ];
            $folder_id = Db::table("wa_folder")->insertGetId($insert);
            $folder = Db::table("wa_folder")->where('id','=',$folder_id)->first();
            if (!$folder){
                return $this->sendnomessage("文件夹不存在");
            }
            $message_id = $message_id != '' ? $message_id : $this->message->get('message_id');
            dump("新建文件夹完成{$message_id}");

            if ($message_id){
                $this->telegram->deleteMessage([
                    'chat_id'   =>   $this->chat_id,
                    'message_id'=> $message_id,
                ]);
            }


            if ($name != "未命名"){
                $text = "文件包被命名为: {$name},接下来请您发送想要加入包的文件吧~\n添加完成后请发送ok, 你也可以点击下面的按钮";
            }else{
                $text = "跳过命名，您可以在之后调整名字。接下来请您发送想要加入包的文件吧~\n添加完成后请发送ok, 你也可以点击下面的按钮";
            }

            // 跳过上传 直接展示菜单
            try {
                $message_param = $this->getFileMessage_tongyi($folder_id,-2);
                $this->telegram->sendMessage($message_param);
                Redis::del($this->rediskey);
            }catch (TelegramResponseException $e) {
                dump($e->getMessage());
            }
            dump("success跳过命名");
            return "success";
        }else{
            $folder = Db::table("wa_folder")->where('link','=',$link)->first();
            if (!$folder){
                return $this->sendnomessage("文件夹不存在");
            }
            $text = "接下来请您发送想要加入包的文件吧~\n添加完成后请发送ok, 你也可以点击下面的按钮";
        }

        $params = [
            'text'  => 'ok',
        ];
        $reply_markup = Keyboard::make()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(true)
            ->setSelective(true)
            ->row([
                Keyboard::button($params),
            ]);

        $res = $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  $text,
            'reply_markup'=> $reply_markup,
        ]);
        dump("消息id是{$res->get("message_id")}");
        $redis_value = [
            "command" => 'fd_upload',
            "link" => $link,
            "folder_id" => $folder->id,
            "folder_name" => $folder->name,
            "message_id" => $res->get("message_id"),
        ];
        Redis::set($this->rediskey,json_encode($redis_value));
        dump("success");
        return "success";
    }

    /**
     *  继承用户 即修改password和 folder的uid
     */
    protected function user_inherit_redis($text,$redisdata){
        Redis::del($this->rediskey);
        $user = Db::table("wa_users")
            ->where('password','=',$text)
            ->first();
        if (!$user){
            return $this->sendnomessage("继承用户失败，请检查您的密钥是否正确");
        }
        if ($user->chat_id ==  $this->chat_id){
            return $this->sendnomessage("您不能继承自己");
        }

        //即修改password和 folder的uid
        Db::table("wa_users")->delete($user->id);
        $this->telegram->sendMessage([
            'chat_id'   =>  $user->chat_id,
            'text'      =>  "您的账户已被继承！！您需要重新发送 /start 重建新的内部用户信息",
        ]);

        $user_now = Db::table("wa_users")
            ->where('chat_id','=', $this->chat_id)
            ->first();
        Db::table("wa_users")
            ->where('chat_id','=', $this->chat_id)
            ->update(['password'=>$text]);

        //继承文件夹
        Db::table("wa_folder")
            ->where('uid','=',$user->id)
            ->update(['uid'=>$user_now->id,'username'=>$user_now->username]);

        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  "您已经成功通过密钥 {$text} 继承用户",
        ]);


        dump("success");
        return "success";
    }
    /**
     *  删除文件
     */
    protected function fd_delete_redis($text,$redisdata){
        $forderid = $redisdata['forderid'];
        if (!$text){
            //删除文件夹
            return $this->delFileLink($forderid);
        }
        if ($text != 'ok'){
            $message_param = [
                'chat_id'       =>   $this->chat_id,
                'text'       =>  "目前您在'从文件夹删除文件'状态，如果想进行别的操作，先发送 ok 退出该状态哦",
            ];
        }else{
//            $this->telegram->editMessageReplyMarkup([
//                'chat_id'   =>   $this->chat_id,
//                'message_id'=> $redisdata['message_id'],
//                'reply_markup' => Keyboard::remove(), // 使用 Keyboard::remove() 移除键盘
//            ]);
            $this->telegram->deleteMessage([
                'chat_id'   =>   $this->chat_id,
                'message_id'=> $redisdata['message_id'],
            ]);
            $message_param = [
                'chat_id'       =>   $this->chat_id,
                'text'       =>  "文件包已修改！",
            ];
            Redis::del($this->rediskey);
        }
        $this->telegram->sendMessage($message_param);
        dump("success");
        return "success";
    }
    /**
     *  修改文件夹名称
     */
    protected function fd_editname_redis($text,$redisdata){
        //修改文件名
        Db::table("wa_folder")->where('id','=',$redisdata['folderid'])->update(['name'=>$text]);
        $param = $this->getFileMessage_tongyi($redisdata['folderid']);
        $param['message_id'] = $redisdata['message_id_folder'];
        $this->telegram->editMessageText($param);
        return $this->xiugai_tongyi("已成功修改名字为'{$text}'",$redisdata['message_id']);
    }
    /**
     *  验证密码获取打包文件
     */
    protected function pk_vertifypassword_redis($text,$redisdata)
    {
        if ($text == "取消"){
            return $this->quxiao_tongyi("已取消密码验证",$redisdata['reply_to_message_id']);
        }else{
            $reply_to_message_id = $this->update->getMessage()->get('message_id');
            if($text == $redisdata['password']){
                //验证密码成功
                $link_arr = $redisdata['link'] ? json_decode($redisdata['link'],true) : [];

                dump("验证密码成功",$link_arr);
                if ($link_arr){
                    Redis::del($this->rediskey);
                    return $this->sendMsgGroup($link_arr,0,['reply_to_message_id'=>$reply_to_message_id]);
                }else{
                    return $this->quxiao_tongyi("暂无文件",$redisdata['reply_to_message_id']);
                }
            }else{
                $text = "密码错误请重新输入";
            }
        }
        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  $text,
            'reply_to_message_id'=> $reply_to_message_id,
        ]);
        dump('success');
        return 'success';
    }
    /**
     *  文字消息 pk_设置密码
     */
    protected function pk_setpassword_redis($text,$redisdata)
    {
        Redis::del($this->rediskey);
        if ($text == "取消"){
            return $this->quxiao_tongyi("取消成功",$redisdata['reply_to_message_id']);
        }else{
            $res = Db::table("wa_package")->where('link', $redisdata['link'])->update(['password' => $text]);
            dump("pk_设置密码{$res}");
            $reply_to_message_id = $redisdata['reply_to_message_id'];
            $text = "<a>文件加密成功，您的提取码为:</a><code>{$redisdata['link']}</code><a>密码设置为:</a><code>{$text}</code>";
        }
        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  $text,
            'parse_mode'=> 'html',
            'reply_to_message_id'=> $reply_to_message_id,
        ]);
        dump('success');
        return 'success';
    }

    /**
     *  设置文件名执行新建文件  后执行添加文件
     */
    protected function fd_setname_redis($text,$redisdata)
    {
        return $this->insertfile_tongyi($text,$redisdata["message_id"]);
    }

    /**
     *  执行添加文件 前置
     */
    protected function fd_upload_redis($text,$redisdata)
    {
        if (!$text){
            return $this->setFileLink();
        }
        if ($text != 'ok'){
            $message_param = [
                'chat_id'       =>   $this->chat_id,
                'text'       =>  "目前您在'向文件夹加入文件'状态，如果想进行别的操作，先发送 ok 退出该状态哦",
            ];
            $this->telegram->sendMessage($message_param);
        }else{
            dump("执行添加文件 前置{$redisdata['message_id']}");
            try {
//                $this->telegram->editMessageReplyMarkup([
//                    'chat_id'   =>   $this->chat_id,
//                    'message_id'=> $redisdata['message_id'],
//                    'reply_markup' => Keyboard::remove(), // 使用 Keyboard::remove() 移除键盘
//                ]);
                $this->telegram->deleteMessage([
                    'chat_id'   =>   $this->chat_id,
                    'message_id'=> $redisdata['message_id'],
                ]);
            }catch (TelegramResponseException $e) {
                dump($e->getMessage());
            }


            $message_param = $this->getFileMessage_tongyi($redisdata['folder_id'],-2);
            $this->telegram->sendMessage($message_param);
            Redis::del($this->rediskey);
        }
        dump("success");
        return "success";
    }
    /**
     *  更新文件状态 无返回
     */
    protected function getFileMessage_tongyi($folderid,$fanhui=-1)
    {
        $forder = Db::table('wa_folder')->where('id','=',$folderid)->where("username",
            $this->update->getChat()?->username)->first();
        if (!$forder){
            return [];
        }
        dump($forder);
        //考虑到继承功能 实时获取
        $count = Db::table('wa_file')->where('forderid','=',$folderid)->count();

        // 上传文件完成
        $forder->name ??= '未命名';
        if ($fanhui < -1){
            $message_param['text'] = "文件夹已创建,如果您需要向文件夹添加文件等操作，请点击下面按钮\n <code>文件夹名称: {$forder->name} \n文件夹分享link: {$forder->link}</code> \n文件总数量: {$forder->filenum} \n被提取过的次数: {$forder->usenum}";
        }else{
            $message_param['text'] = "<code>文件夹名称: {$forder->name} \n文件夹分享link: {$forder->link}</code> \n文件总数量: {$forder->filenum} \n被提取过的次数: {$forder->usenum}";
        }

        $zhuanfatext = $forder->zhuanfa == 1 ? '可以' : "不可以";
        $tiqutext = $forder->tiqu == 1 ? '可以' : "不可以";
        $reply_markup = Keyboard::make()
            ->inline()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(false)
            ->setSelective(true)
            ->row([
                Keyboard::button(['text'=>'添加文件','callback_data'=>"fd_add {$forder->id}"]),
                Keyboard::button(['text'=>'删除文件','callback_data'=>"fd_delete {$forder->id}"]),
                Keyboard::button(['text'=>'一键提取','callback_data'=>"fd_getlink {$forder->id}"]),
            ])->row([
                Keyboard::button(['text'=>'修改名字','callback_data'=>"fd_editname {$forder->id}"]),
                Keyboard::button(['text'=>'修改分享链接','callback_data'=>"fd_editlink {$forder->id}"]),
            ])->row([
                Keyboard::button(['text'=>"当前提取后的内容{$zhuanfatext}转发",'callback_data'=>"fd_zhuanfa_y {$forder->id}"]),
            ])->row([
                Keyboard::button(['text'=>"当前其他人{$tiqutext}提取文件夹",'callback_data'=>"fd_tiqu_y {$forder->id}"]),
            ])->row([
                Keyboard::button(['text'=>'删除此文件夹','callback_data'=>"fd_shanchu {$forder->id}"]),
            ]);
        if ($fanhui >= 0 ){
            $reply_markup->row([
                Keyboard::button(['text'=>'返回','callback_data'=>"fd_chakanlist {$fanhui}"]),
            ]);
        }

        $message_param['parse_mode'] = 'html';
        $message_param['reply_markup'] = $reply_markup;
        $message_param['chat_id'] =  $this->chat_id;
        return $message_param;
    }

    /**
     *  更新我的文件夹列表 无返回
     */
    protected function getMyFolderMessage_tongyi($page=0)
    {
        dump("getMyFolderMessage_tongyi");
        $offset = $page*5;
        $file_arr = Db::table("wa_folder")
            ->where("username",$this->update->getChat()?->username)
            ->where("uid",$this->user_now->id)
            ->offset($offset)->limit(5)->get();
        dump($file_arr);
        if (!$file_arr){
            return $this->sendnomessage("暂无数据");
        }
        $count = Db::table("wa_folder")
            ->where("username",$this->update->getChat()?->username)->count();
        $Keyboard = [];
        $aa = '';
        foreach ($file_arr as $k => $v){
            $aa .= "序号 ".($offset+1+$k).": {$v->name}  | 文件总数量 {$v->filenum} |\n";
            $Keyboard[] =  Keyboard::button(['text'=>"查看".($offset+1+$k),'callback_data'=>"fd_chakan {$v->id} {$page}"]);
        }
        $a = "您创建的文件夹".($offset+1)." ~ ".($offset+5)."(当前第".($page+1)."页,共".ceil($count/5)."页)：\n{$aa}请使用下面的按钮选取一个文件夹进行查看或翻页查看其余创建的文件夹";
        $Keyboard2 = [];
        //有上一页
        if ($page > 0){
            if (ceil($count/5) >= 11){
                $Keyboard2[] = Keyboard::button(['text'=>"首页",'callback_data'=>"fd_chakanlist 0"]);
            }
            $Keyboard2[] = Keyboard::button(['text'=>"上一页",'callback_data'=>"fd_chakanlist ". ($page-1)]);
        }
        //有下一页
        if ($count > ($offset+5)){
            $Keyboard2[] = Keyboard::button(['text'=>"下一页",'callback_data'=>"fd_chakanlist ".($page+1)]);
            if (ceil($count/5) >= 11){
                $Keyboard2[] = Keyboard::button(['text'=>"尾页",'callback_data'=>"fd_chakanlist ".(ceil($count/5)-1)]);
            }
        }

        $reply_markup = Keyboard::make()
            ->inline()
            ->setResizeKeyboard(true)
            ->setOneTimeKeyboard(false)
            ->setSelective(true)
            ->row($Keyboard)->row($Keyboard2);

        $message_param['text'] = $a;
        $message_param['reply_markup'] = $reply_markup;
        $message_param['chat_id'] =  $this->chat_id;
        return $message_param;
    }

    /**
     *  删除文件
     */
    protected function delFileLink($forderid){
        $type = $this->message->objectType();
        $link = $this->setLink($type);
        dump($type);
        dump($link);
        dump($forderid);
        $res = Db::table("wa_file")
            ->where("link",'=',$link)
            ->where("forderid",'=',$forderid)
            ->delete();
        if ($res){
            $text = "您已从文件夹中删除此文件";
            DB::table('wa_folder')->where("id",'=',$forderid)->decrement('filenum');
        }else{
            $text = "文件夹中没有此文件";
        }
        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  $text,
            'reply_to_message_id'      =>  $this->message->get("message_id"),
        ]);

        dump("success2222");
        return "success";
    }

    /**
     *  存储文件,处理文件信息,执行添加文件
     */
    protected function setFileLink(){
        $type = $this->message->objectType();
//        $file_id = $this->getFileId($this->message,$this->message->objectType());
        $file_id = $this->getFileId2($this->message->$type,$type);

        //获取文件名,文件id
        $fordemame = '未命名';
        $forderid = 0;
        $redisData = Redis::get($this->rediskey);
        $redisData = $redisData ? json_decode($redisData,true) : [];
        if ($redisData){
            $link = $redisData['link'];
            $forder = Db::table('wa_folder')->where('link','=',$link)->where("username",$this->update->getChat()
                ?->username)->first();
            $forder = $forder ? (array)$forder : [];
            if ($forder){
                $fordemame = $forder['name'];
                $forderid = $forder['id'];
            }
        }

        $link = $this->setLink($type);
        $existingRecord = Db::table("wa_file")
            ->where('link','=',$link)
            ->where('uid','=',$this->user_now->id)
            ->where('forderid','=',$forderid)
            ->first();
        if ($existingRecord){
            return $this->sendnomessage("文件已存在");
        }
        $insert = [
            'link' => $link,
            'type' => $type,
            'fleinfo' => $this->message->get($type)->toJson(),
            'username' =>$this->update->getChat()->username,
            'chatid' => $this->update->getChat()->id,
            'group' => $this->update->get("media_group_id") ?? '',
            'bot' => $this->bot_name,
            'update_id' => $this->update->get("update_id"),
            'fordemame' => $fordemame,
            'forderid'  => $forderid,
            'uid'  => $this->user_now->id,
            'created_at' => date("Y-m-d H:i:s",time()),
            'updated_at' => date("Y-m-d H:i:s",time()),
        ];
        $res = Db::table("wa_file")->upsert($insert,['link','username']);
        dump("新增文件结果{$res}");
        if ($res){
            DB::table('wa_folder')->where("id",'=',$forderid)->increment('filenum');
        }


        //此处实时备份
        RedisQueue::send('setbei_file',['file_id' => $file_id,'type' => $type]);

        //$this->beifen($file_id,$type);

        if (!$forderid){
            $this->telegram->sendMessage([
                'chat_id'   =>   $this->chat_id,
                'text'      =>  "此条文件分享link: <code>{$link}</code>",
                'parse_mode'      =>  "html",
                'reply_to_message_id'      =>  $this->message->get('message_id'),
            ]);
        }

        dump("success");
        return "success";
    }
    /**
     *  发送文件夹
     */
    protected function sendMsgGroup($link_arr,$forderid=0,$message_extra=null)
    {
        dump($link_arr);
        //整理文件夹
        $media = [];
        $file_arr = Db::table("wa_file")
            ->whereIn("link",$link_arr)
            ->where("uid",$this->user_now->id)
            ->where("forderid",$forderid)
            ->where("bot",'=',$this->bot_name)
            ->get();
        if (!$file_arr){
            return $this->sendnomessage("暂无数据");
        }
        foreach ($file_arr as $k => $v){
            $media[$k] = [
                'type' => $v->type,
                'media' => $this->getFileId2($v->fleinfo),
            ];
            if ($k==1 && $message_extra['caption']){
                $media[$k]['caption'] = $message_extra['caption'];
            };
        }

        if (!$media){
            return $this->sendnomessage("暂无数据");
        }
        $message_param = [
            'chat_id' =>  $this->chat_id,
            "media"     =>  json_encode($media),
            "reply_to_message_id" =>$this->update->getMessage()->get('message_id'),
        ];
        if ($message_extra){
            $message_param  = array_merge($message_param,$message_extra);
        }
        try {
            $this->telegram->sendMediaGroup2($message_param);
        }catch (TelegramResponseException $e) {
            dump($e->getMessage());
        }

        dump('success');
        return 'success';
    }

    /**
     *  发送无消息
     */
    protected function sendnomessage($text=null)
    {
        $text = $text??"未找到文件";
        $this->telegram->sendMessage([
            'chat_id'   =>   $this->chat_id,
            'text'      =>  $text,
        ]);
        dump("sendnomessage");
        return 'success';
    }
    /**
     *  发送文本消息统一
     *  reply_markup 按钮
     *  parse_mode html
     */
    protected function sendmessage_tongyi($text=null,$reply_to_message_id=null,$message_extra=null)
    {
        $message_param = [
            'chat_id'   =>   $this->chat_id,
        ];
        $text = $text ?? "未找到文件";
        $message_param['text'] = $text;
        if ($reply_to_message_id){
            $message_param['reply_to_message_id'] = $reply_to_message_id;
        }
        if ($message_extra){
            $message_param = array_merge($message_param,$message_extra);
        }
        $this->telegram->sendMessage($message_param);
        dump("发送文本消息success");
        return 'success';
    }


    /**
     * 设置提取码
     */
    protected function setLink($type,$linktxt = '')
    {
        $qian = Db::table("bot_file_perfix")->where("type",'=',$type)->value("perfix");
        $qian = $qian ?? 'F_';
        if (!$linktxt){
            //获取 file_unique_id 组成名称`
            $linktxt = '';
            $info = $this->message->get($type)->toArray();
            if (!isset($info['file_unique_id'])){
                foreach ($info as $v) {
//                    $linktxt .= substr($v['file_unique_id'],6);
                    $linktxt .= $v['file_unique_id'];
                }
            }else{
//                $linktxt = substr($info['file_unique_id'],6);
                $linktxt = $info['file_unique_id'];
            }
        }
        $link = $qian.md5($linktxt);
        return $link;
    }

    /**
     * 处理命令行
     */
    protected function deal_command($command,$text_arr = '')
    {
        $message = $this->message;
        $message_param = [];
        dump("deal_command");
        dump($command);
        dump($command->type);
        switch ($command->type) {
            case "start":  //新注册用户
                dump("处理start");
                //处理start 注册成为会员
                $from = $message->from->toArray();
                $from['chat_id'] = $from['id'];
                $from['chat_bot'] = $this->bot_name;
                $from['password'] = md5($from['username'].'-'.time());
                unset($from['id']);
                unset($from['is_bot']);
                $res = Db::table("wa_users")->upsert($from,['chat_id','chat_bot']);
                dump("注册会员:{$res}");
                break;
            case "pk":      //打包文件

                break;
            case "myfd":   //我的文件夹
                if (isset($text_arr[1])){
                    $page = floor(intval($text_arr[1]) / 5);
                }else{
                    $page = 0;
                }
                $message_param =  $this->getMyFolderMessage_tongyi($page);
                break;
            case "my":   //会员中心
                $user = Db::table("wa_users")
                    ->where('username','=',$this->update->getChat()?->username)
                    ->first();
                $count = Db::table("wa_folder")
                    ->where('uid','=',$this->user_now->id)
                    ->count();
                $file_count = Db::table("wa_folder")
                    ->where('uid','=',$this->user_now->id)
                    ->sum("filenum");
                $message_param['text'] = "当前用户id: {$user->chat_id}\n找回账户密钥: {$user->password}\n文件夹数量: {$count}\n文件总数量: {$file_count}\n\n请妥善保管好您的找回用密钥，同时千万不要告诉其他人！";
                break;
            case "inherit":   //找回备份
                dump("找回备份");
                $redis_value = [
                    "command" => 'user_inherit',
                ];
                Redis::set($this->rediskey,json_encode($redis_value));
                break;
            case "fd":      //新建文件夹
                $params1 = [
                    'text'                                 => '跳过取名',
                    'callback_data'                        => 'fd_tiaoguo',
                ];
                $params2 = [
                    'text'                                 => '取消创建',
                    'callback_data'                        => 'fd_quxiao',
                ];
                $reply_markup = Keyboard::make()
                    ->inline()
                    ->setResizeKeyboard(true)
                    ->setOneTimeKeyboard(true)
                    ->row([
                        Keyboard::button($params1),
                        Keyboard::button($params2),
                    ]);
                $message_param['reply_markup'] = $reply_markup;

                break;
            default:
                dump("txt类型不处理");
                break;
        }
        if ($command->value && !isset($message_param['text'])){
            $message_param['text'] = $command->value;
        }
        if ($message_param){
            $message_param["chat_id"] =  $this->chat_id;
            $res = $this->telegram->sendMessage($message_param);

            //后置执行
            if($command->type == 'fd'){
                $redis_value = [
                    "command" => 'fd_setname',
                    "message_id" => $res->get('message_id'),
                ];
                Redis::set($this->rediskey,json_encode($redis_value));
            }

        }
        dump("success");
        return "success";
    }

    /**
     * 整理数据 获取field_id
     */
    protected function formatMessage($type,$method,$file_path)
    {
        $token = $this->beifen_token;
        $telegram = new Api($token);
        $response = $telegram->{$method}([
            'chat_id' => $this->beifen_id,
            $type => InputFile::create("https://api.telegram.org/file/bot{$token}/{$file_path}"),
            'caption' => '备份文件'
        ]);
    }
    /**
     * 备份数据 无返回 放队列了
    */
    protected function beifen($file_id,$type)
    {
        $token = $this->beifen_token;
        $telegram = new Api($token);
        $method  = 'send'. ucfirst(Str::camel($type));

        $file = $telegram->getFile([
            'file_id'   =>  $file_id,
        ]);

        $response = $telegram->{$method}([
            'chat_id' => $this->beifen_id,
            $type => InputFile::create("https://api.telegram.org/file/bot{$token}/{$file->file_path}"),
            'caption' => '备份文件'
        ]);
        dump("备份结果:{$response->toJson()}");
//        return $this->getFileId($response,$type);
    }
    /**
     * 获取 file_id
     */
    protected function getFileId($response,$type)
    {
        if ($type == 'photo'){
            $file_id =  data_get($response->{$response->objectType()},'0.file_id');
        }else{
            $file_id = $response->{$response->objectType()}->file_id;
        }
        return $file_id;
    }
    /**
     * 根据文件信息获取file_id
     */
    protected function getFileId2($fileinfo,$type = '')
    {
        if (gettype($fileinfo) == "string"){
            $fileinfo = json_decode($fileinfo,true);
        }else{
            $fileinfo = $fileinfo->toArray();
        }
        if (isset($fileinfo['file_id'])){
            $file_id = $fileinfo['file_id'];
        }else{
            $file_id = $fileinfo[count($fileinfo)-1]['file_id'];
        }
        return $file_id;
    }
    /**
     * 设置命令
     */
    public function setMyCommands()
    {
        //        设置命令
        $telegram = new Api($this->bot_bottoken);

        $wa_command = Db::table("wa_command")->where("isindex",'=',1)->orderBy('order','desc')->get(['name','intro'])
            ->toArray();
        $MyCommands = [
            "commands" =>[]
        ];
        foreach ($wa_command as $v){
            $MyCommands['commands'][] = [
                "command" => $v->name,
                "description" => $v->intro,
            ];
        }
        dump($MyCommands);

        $res = $telegram->setMyCommands($MyCommands);
        dump($res);
        $params = [
            'menu_button' => json_encode(
                array (
                    "type" => "commands",
                )
            )
        ];
        $res = $telegram->setChatMenuButton($params);
        dump($res);
        return $res;
    }

}
